import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/add_entrance_guard/index.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/api.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/detail/index.dart";
import "package:ct_pa_majordomo/pages/device/entrance_guard/widgets/list_item.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/router/keys.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/empty_data/index.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_dropdown.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/filter_header.dart";
import "package:ct_pa_majordomo/widgets/filter_layout/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";

class EntranceGuard extends StatefulWidget {
  const EntranceGuard({super.key});

  @override
  State<StatefulWidget> createState() => _EntranceGuardState();

}

class _EntranceGuardState extends State<EntranceGuard> {
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  final Map _filter = {"pageNum": 1};
  final List _status = [{"name": "全部"}, {"name": "未关联房间"}];
  List _list = [];
  int _total = 0;
  final List<FilterHeaderItem> _headerItems = [
    FilterHeaderItem(title: "状态"),
    FilterHeaderItem(
      title: "数量：0",
      render: (title) {
        return Text(
          title,
          textAlign: TextAlign.center,
          style: const TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
          ),
        );
      },
    ),
  ];

  Future<void> _getEntranceGuardList() async {
    try {
      Map<String, dynamic> params = {..._filter, "pageSize": 10};
      _isLoading = true;
      Map resData = await entranceGuardApi.getEntranceGuardList(params);
      _isLoading = false;
      List data = resData["rows"] ?? [];
      setState(() {
        _total = resData["total"] ?? 0;
        _headerItems.last.title = "数量：$_total";
        _list.addAll(data);
      });
    } catch (error) {
      print(error);
    }
  }
  
  Future<void> _refresh() async {
    _list = [];
    _filter["pageNum"] = 1;
    _getEntranceGuardList();
  }
  
  void _onScroll() {
    if (_isLoading || _list.length >= _total) return;
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      setState(() {
        _filter["pageNum"] += 1;
        _getEntranceGuardList();
      });
    }
  }

  @override
  void initState() {
    super.initState();
    _getEntranceGuardList();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
        title: "门禁",
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios_new),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        onSearch: (value) {
          setState(() {
            _filter["pageNum"] = 1;
            _filter["name"] = value;
          });
          // _getElectricityList();
        },
        showFloatBtn: true,
        floatOnPress: () {
          Stacker.pushNamed(Keys.DEVICE_ADD_ENTRANCEGUARD).then((value) {
            if (value != null) {
              if (value as bool) _refresh();
            }
          });
        },
        children: [
          FilterLayout(
            headerItems: _headerItems,
            dropdownItems: [
              FilterDropdownItem(
                items: _status,
                itemAsString: (item) => item["name"],
              ),
            ],
            child: RefreshIndicator(
              onRefresh: _refresh, 
              child: _list.isEmpty ? ListView(
                children: [ EmptyData() ],
              ) : ListView.separated(
                physics: const AlwaysScrollableScrollPhysics(),
                padding: const EdgeInsets.all(ThemeVars.paddingPage),
                itemBuilder: (context, index) {
                  return GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      Stacker.pushNamed(Keys.DEVICE_ENTRANCEGUARD_DETAIL, arguments: _list[index]["faceLockId"]).then((value) {
                        if (value != null && value as bool) _refresh();
                      });
                    },
                    child: ListItem(info: _list[index],),
                  );
                },
                separatorBuilder: (context, index) => const SizedBox(height: 15),
                itemCount: _total,
              ),
            )
          ),
        ]
    );
  }

}